<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2018/12/23
 * Time: 22:55
 */

namespace App\Http\Controllers\Admin;


use App\Models\Brand;
use App\Models\Product;
use App\Models\User;
use App\Models\UserProducts;
use App\Services\UserService;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function overview(UserService $userService)
    {
        // 活动参与次数
        $userProducts = UserProducts::all();
        $pv = $userProducts->count();
        $uv = $userProducts->unique('user_id')->count();

        $brands = Brand::all();
        $brandCount = $brands->count();
        $pickedBrandCount = $brands->where('picked_count', '>', 0)->count();

        $products = Product::all();
        $productCount = $products->count();
        $pickedProductCount = $products->where('picked_count', '>', 0)->count();

        // 性别比例
        $genders = $userService->getGenderProportion();

        // 品牌top10
        $topBrands = Brand::query()->orderBy('picked_count', 'desc')->limit(10)->get(['name', 'picked_count']);

        $topBrandsRes = $topBrands->sortBy('picked_count')->mapWithKeys(function ($item) {
            return [$item['name'] => $item['picked_count']];
        });

        // 商品top10
        $topProducts = Product::query()->orderBy('picked_count', 'desc')->limit(10)->get(['name', 'picked_count']);
        $topProductsRes = $topProducts->sortBy('picked_count')->mapWithKeys(function ($item) {
            return [$item['name'] => $item['picked_count']];
        });

        $data = [
            'info_card' => [
                'pv' => $pv,
                'uv' => $uv,
                'brand_count' => $brandCount,
                'picked_brand_count' => $pickedBrandCount,
                'product_count' => $productCount,
                'picked_product_count' => $pickedProductCount,
            ],
            'gender_proportion' => $genders,
            'top_brands' => $topBrandsRes,
            'top_products' => $topProductsRes,
        ];

        return $this->success($data);
    }
}